from datetime import datetime

import schedule
import time
from libs.Objects import Objects
from libs.StockBase import StockBase
from StockProcessor import StockProcessor
from EmailSender import EmailSender
from StockDownloader import StockDownloader
from StockToFile import StockToFile
from StockHotReview import StockHotReview

emailSender = EmailSender()

stock = StockDownloader()


def task_download_history():
    handler = StockDownloader()
    startDay = Objects.getDay(-10)
    endDay = Objects.getCurrDay()
    handler.downloadTradingData(startDay=startDay, endDay=endDay)


def prevProcess(currDay):
    print(str(currDay) + " START")
    StockBase().getBaostock().login()
    StockBase().getStockBasic()


def afterProcess(currDay):
    # StockBase().exit()
    print(str(currDay) + " OVER")


# stdout: time 2025-01-19T17:30:00.000153,traing 2025-01-17 processTask
def processTask():
    currDay = None
    # currDay='2024-02-14'
    if currDay is None:
        currDay = Objects.getCurrDay()
    prevProcess(currDay)
    print("开始任务 time %s,trading %s processTask" % (str(datetime.today().isoformat()), currDay))

    task_download_history()
    result_file = "data/%s_stock.xlsx" % (currDay)
    if StockBase().isTradingDate(currDay):
        stock.downTradingData(currDay)
        toFile = StockToFile()
        if not toFile.if_exist(currDay):
            print("StockProcessor().process")
            StockProcessor().process(currDay, currDay)

        df = toFile.query_to_df(endDay=currDay)
        limit_up_df = toFile.convert_result(df)

        hotReview = StockHotReview()
        if not hotReview.if_exist(currDay):
            print("hotReview.save_data")
            hotReview.save_data(currDay)
        df = hotReview.query_to_df(endDay=currDay)
        hot_df = hotReview.convert_columns(df)

        print("Objects.to_excel")
        Objects.to_excel(result_file, hot_df, limit_up_df)
        emailSender.trading_date(currDay, result_file)

        ##    ZIP_FILE = 'data/all_trading_data.zip'
        ##    Objects.zipFile('data/trading', ZIP_FILE)
        ##    emailSender.trading_data(currDay, ZIP_FILE)
    else:
        emailSender.not_trading_date(currDay)
    afterProcess(currDay)


# 当前交易日17:30，完成日K线数据入库；
schedule.every().day.at("17:35").do(processTask)


# schedule.every(1).minute.do(task)

def downBasicStock():
    print("下载股票基础数据")
    stock = StockDownloader()
    stock.downloadStockBasic()


schedule.every().monday.at("08:30").do(downBasicStock)

if __name__ == '__main__':
    time.sleep(1)
    print('time %s welcome stock processor!  %s  ' % (datetime.today().isoformat(), str(Objects.getCurrDay())))
    # downBasicStock()
    processTask()
    while True:
        schedule.run_pending()
